What is $rootScope in AngularJS?
156
20-Jun-2024
Updated on 20-Jun-2024
Ashutosh Kumar Verma
20-Jun-2024$rootScope in AngularJS
In AngularJS,
$rootScope
is the parent scope created by the AngularJS framework itself. It sits at the top of the scope hierarchy for an AngularJS application.What is $rootScope in AngularJS?
$rootScope is the biggest scope in AngularJS applications, it acts as the parent scope for all other scopes.
How does $rootScope differ from conventional scopes?
$rootScope is global and accessible throughout the application, whereas regular scopes are limited to their controllers or directives.
What are the common expressions for $rootScope?
Sharing global data, defining global services, and using an event system ($emit, $broadcast, $on) for communication between parties.
How does $rootScope facilitate component communication?
It provides $emit, $broadcast, and $on methods for triggering and listening for events in different parts of the application.
Best practices when using $rootScope?
Use the global namespace sparingly to avoid clutter, prioritize tasks for data sharing, and focus on business specifications for broad events.
Example-
In the example above
The
globalVar
defined in$rootScope
can be accessed by any controller or directive in the application.$rootScope.$on('someEvent', ...) Listens for events sent from any part of the application.
$rootScope.$broadcast('someEvent', ...) Creates an event that
$rootScope.$on
or $scope.$on can catch in child scopes.Also, Read: Explain the concept of "ng-repeat" in AngularJS